package com.hc.server.listener;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.TimerTask;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hc.server.Config;
import com.hc.server.conn.mall.MallServerHelper;
import com.hc.server.db.DBFactory;
import com.hc.server.db.Mporder;
import com.hc.server.db.Ordermap;

public class UnlockResTask extends TimerTask {

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		System.out.println("refresh locked res!");
		//搜索所有待支付的订单
		String hql = "from Mporder as mpo where mpo.status = 2 and mpo.invalidTime < :now";
		Session session = DBFactory.openSession();
		Transaction t = session.beginTransaction();
		try{
			t.begin();
			Query query = session.createQuery(hql);
			query.setParameter("now", new Date());
			Iterator<Mporder> orderIter = query.iterate();
			while (orderIter.hasNext()) {
				Mporder mpo = orderIter.next();
				//将超过时限的订单释放占用的资源
				Set<Ordermap> map = mpo.getOrdermaps();
				Iterator<Ordermap> mapIter = map.iterator();
				while(mapIter.hasNext()){
					Ordermap tmp = mapIter.next();
					String mallOrderId = tmp.getMallorderId();
					//TODO： 取消操作可能出现异常，如何处理？
					MallServerHelper.cancelOrder(mallOrderId);
				}
				//修改订单的状态
				mpo.setStatus(Config.ORDER_INVALID);
				session.saveOrUpdate(mpo);
			}
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();
			t.rollback();
		} finally {
			session.close();
		}
	}

}
